package com.njym.java.security.app.rest;


import com.njym.java.security.app.biz.FamilyUserGroupsBiz;
import com.njym.java.security.app.biz.GroupsMsgContentBiz;
import com.njym.java.security.app.biz.UserGroupsToUserBiz;
import com.njym.java.security.app.entity.FamilyUserGroups;
import com.njym.java.security.app.entity.FamilyUserGroupsVo;
import com.njym.java.security.app.entity.GroupsMsgContent;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.util.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("familyUserGroups")
public class FamilyUserGroupsController extends BaseController<FamilyUserGroupsBiz,FamilyUserGroups> {
    private final Log logger = LogFactory.getLog(UserRelationController.class);
    @Autowired
    private PlatformTransactionManager txManager;
    @Autowired
    private UserGroupsToUserBiz userGroupsToUserBiz;
    @Autowired
    private FamilyUserGroupsBiz familyUserGroupsBiz;
    @Autowired
    private GroupsMsgContentBiz groupsMsgContentBiz;
    /**
     * 查询群详情
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/queryGroupDetail",method = RequestMethod.GET)
    @ResponseBody
    public Object queryGroupDetail(String groupId){
        if (!groupId.equals("undefined")) {
            List<FamilyUserGroupsVo> list = baseBiz.queryGroupDetail(Integer.parseInt(groupId));
            Map<String, Object> data = new HashMap<>(1);
            data.put("list", list);
            return new ObjectRestResponse<FamilyUserGroups>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 更改群名 群公告
     * @param id
     * @param ugName
     * @param ugNotice
     * @return
     */
    @RequestMapping(value = "/updateGroup",method = RequestMethod.GET)
    @ResponseBody
    public Object updateGroup(String id, String ugName, String ugNotice, String ugIcon){
        if (!id.equals("undefined")) {
            FamilyUserGroups familyUserGroups = new FamilyUserGroups();
            familyUserGroups.setId(Integer.parseInt(id));
            familyUserGroups.setUgName(ugName);
            familyUserGroups.setUgNotice(ugNotice);
            familyUserGroups.setUgIcon(ugIcon);
            baseBiz.updateSelectiveById(familyUserGroups);

            Map<String, Object> data = new HashMap<>(1);
            return new ObjectRestResponse<FamilyUserGroups>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    /**
     * 退出群聊
     * @param groupId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/quitGroup",method = RequestMethod.GET)
    @ResponseBody
    public Object quitGroup(String groupId, String userId){
        if (!userId.equals("undefined") && !groupId.equals("undefined")) {
            Map<String, Object> data = new HashMap<>(1);
            // 开启事务管理
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);
            try {
                //删除usergroupstouser表
                userGroupsToUserBiz.quitGroupTo(Integer.parseInt(groupId), Integer.parseInt(userId));
                //删除聊天记录
                groupsMsgContentBiz.deleteByFromId(Integer.parseInt(groupId), Integer.parseInt(userId));
                //群人数减1
                familyUserGroupsBiz.reduceNum(Integer.parseInt(groupId));

            }catch (Exception ex) {
                txManager.rollback(status);
                logger.error("网络连接超时", ex);
                return new ObjectRestResponse<FamilyUserGroups>().rel(true).data(data);
            }
            txManager.commit(status);

            return new ObjectRestResponse<FamilyUserGroups>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 解散群聊
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/dissolveGroup",method = RequestMethod.GET)
    @ResponseBody
    public Object dissolveGroup(String groupId){
        if (!groupId.equals("undefined")) {
            Example example = new Example(GroupsMsgContent.class);
            example.createCriteria().andEqualTo("attr2", Integer.parseInt(groupId));
            // 开启事务管理
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);

            try {
                //删除usergroupstouser表
                userGroupsToUserBiz.dissolveGroupTo(Integer.parseInt(groupId));
                //删除群聊记录
                groupsMsgContentBiz.deleteByGroupId(Integer.parseInt(groupId));
                //删除group
                familyUserGroupsBiz.deleteById(Integer.parseInt(groupId));

            }catch (Exception ex) {
                txManager.rollback(status);
                logger.error("网络连接超时", ex);
            }
            txManager.commit(status);

            Map<String, Object> data = new HashMap<>(1);
            return new ObjectRestResponse<FamilyUserGroups>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }


    }
}